import Util from "./Util";
import GameMain from "../shooting/GameMain";

const {ccclass, property} = cc._decorator;

// 所有敌人的基类，所有敌人都继承该类
@ccclass
export default class Enemy extends cc.Component {


    // 敌人默认的生命值
    @property()
    healthPoint: number = 1;
    @property()
    score:number = 1;
    // 敌人拥有的子弹种类
    @property(cc.Prefab)
    bullets: cc.Prefab[] = [];
    // 发射子弹的速度
    @property()
    shootSpeed: number = 0.5;
    // 敌人移动一次的步长
    speed: number = 2;
    timer: number = 0;

    // 初始化敌人
    start() {
        this.reset();
    }

    reset() {
        this.healthPoint = 1;
        let minX = -this.node.parent.width / 2 + this.node.width / 2; //最小X坐标；
        let maxX = Math.abs(minX);
        let maxY = this.node.parent.height / 2 + this.node.height; //最小Y坐标；
        let util = new Util();
        let x = Math.floor(util.random(minX, maxX));
        this.node.setPosition(new cc.Vec2(x, maxY));
    }

    update(dt: number) {
        this.timer += dt;
        this.shootBullet();
        if (GameMain.running) {
            this.move();
        }else{
            this.node.destroy();
        }
    }

    // 机体发射子弹
    shootBullet() {
        if (this.timer - this.shootSpeed > 0) {
            if (this.bullets.length > 0) {
                this.timer = 0;
                let loadobj = cc.instantiate(this.bullets[0]);//将预制体克隆到场景
                this.node.parent.addChild(loadobj);//将克隆出的物体作为子物体
                loadobj.setPosition(cc.v2(this.node.x, this.node.y));
            }
        }
    }




    beInjured(damage: number) {
        console.log("受伤害了");
        this.healthPoint -= damage;
        if (this.healthPoint <= 0) {
            this.node.destroy();
            GameMain.score += this.score;
        }
    }

    protected move(): void {
        this.node.y -= this.speed;
    }

    protected onDestroy(): void {
        console.log("敌人被销毁")
    }
}
